﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace System
{
    /// <summary>
    /// 
    /// <para>by tangjingbo at 2009-3-27 14:33</para>
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// 获取当前枚举值 Description 的值
        /// <para>by tangjingbo at 2009-3-27 14:33</para>
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string GetDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            if (fi == null)
                return value.ToString();
            DescriptionAttribute[] attributes =
            (DescriptionAttribute[])fi.GetCustomAttributes(
            typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();

        }
        /// <summary>
        /// 
        /// <para>by tangjingbo at 2009-3-27 14:55</para>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string GetDescription<T>(this Enum value) where T : Attribute
        {
           
            T t = GetTAttribue<T>(value);
            return (t != null) ? t.ToString() : value.ToString();
        }
        /// <summary>
        /// 
        /// <para>by tangjingbo at 2009-3-27 14:57</para>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static T GetTAttribue<T>(this Enum value) where T : Attribute
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            if (fi == null)
                return null;
            T[] attributes = (T[])fi.GetCustomAttributes(typeof(T), false);
            return (attributes.Length > 0) ? attributes[0] : null;
        }
    }
}
